<script setup>
import {ref, watch, onMounted,toRaw} from 'vue';
import axios from 'axios'; // 确保你已正确配置 axios
import {userStore} from '@/store/index.js';
import {ElMessage, ElDialog, ElButton, ElIcon, ElDivider, ElPopover} from 'element-plus';
import {ShoppingCartFull, Close} from '@element-plus/icons-vue';
import {useRouter} from 'vue-router';

const store = userStore();
const router = useRouter();

const topPage = ref({}); // 热销榜页面对象
const param = ref({
  pageNum: 1, // 当前页码
  pageSize: 8, // 每页大小
  type:0,
}); // 页码参数

const visibleInner = ref(false); // 内部是否可见的属性
const good = ref({}); // 显示的书籍

// 查询排名的书籍 热销榜
const query = async () => {
  try {
    const resp = await axios.post('/goods/findAll', param.value);
    topPage.value = resp.data;
    console.log("加载商品",topPage.value);
  } catch (error) {
    console.error('', error);
  }
};

// 页码变化
const handleChangePage = (val) => {
  param.value.pageNum = val;
  console.log("页码变化",val)
  query();
}

// 监听 props 的变化
watch(() => visibleInner.value, (newVal) => {
  console.log("newVal", newVal);
  if (newVal) {
    findById();
  }
});

const goodId = ref(null)
// 通过 id 查询一本书籍
const findById = async () => {
  try {
    const resp = await axios.get(`/goods/findById/${goodId.value}`);
    good.value = resp.data; // 查询到的数据
  } catch (error) {
    console.error('', error);
  }
}

// 点击图片触发事件
const showDetail = (id) => {
  goodId.value = id;
  visibleInner.value = true;
}
// 关闭对话框
const handlerClose = () => {
  visibleInner.value = false;
}
// 加入购物车
const addCart = (goodId) => {
  // 判断是否登录
  if (!store.loggedIn) {
    ElMessage.info("请先登录后再添加商品到购物车");
    router.push('/login').catch(err => err);
    return;
  }
  axios.post(`/cart/add/${goodId}`).then(resp => {
    ElMessage.success("成功添加商品到购物车");
    // 关闭弹框
    handlerClose();
  }).catch(error => {
    ElMessage.error("添加购物车失败！");
  });
}

const selectedItems = ref({});
const buy = (good) => {
  console.log("点击立即购买，拿到的数据",good)
  selectedItems.value = good;
  selectedItems.value.quantity = 1
  selectedItems.value.goodsId = good.id;
  selectedItems.value.sumPrice = good.price;
  selectedItems.value.amount = 1
  selectedItems.value.totalPrice = good.price;
  console.log("封装后的数据", selectedItems.value);
  // 判断是否登录
  if (!store.loggedIn) {
    ElMessage.info("请先登录后再添加商品到购物车");
    router.push('/login').catch(err => err);
    return;
  }
  // 将选中的商品信息转换为普通对象
  const rawSelectedItem = toRaw(selectedItems.value);
  const selectedItemsData = JSON.stringify(rawSelectedItem);
  console.log("selectedItemsData", selectedItemsData);
  router.push({//跳转到结算页面
    path: '/buySettlement',
    query: { selectedItems: selectedItemsData }
  }).catch(error => error);
}
const activeName = ref('0');
const handleClick = (tab) => {
  queryByStatus(tab.props.name);
  param.value.type = tab.props.name
};
const queryByStatus = (status) => {
  param.value.type = status;
  console.log("type",status);
  axios.post('/goods/findByType',param.value)
      .then((resp) => {
        topPage.value = resp.data;
      })
      .catch((error) => {
        ElMessage({ type: 'error', message: error, showClose: true })
      });
};
const orderStatus = ref({ '0': '商品', '1': '专业养护', '2': '车载电子', '3': '外观形象', '4': '生活格调', });

onMounted(() => {
  // query();
  queryByStatus('0')
});
</script>

<template>
  <div>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane :label="value" :name="key" v-for="(value, key, index) in orderStatus" :key="index">
        <el-row :gutter="20"><!-- 图片展示 ，gutter：设置每个列之间间隔 -->
          <el-col :span="6" v-for="good in topPage.records" :key="good.id" style="margin-bottom: 25px;">
            <!-- shadow="hover"鼠标移上才显示阴影 ,当卡片任意处被点击，触发事件，显示详情-->
            <el-card :body-style="{ padding: '8px' }" shadow="hover" @click="showDetail(good.id)">
              <!-- 显示图片 -->
              <el-image style="width: 100%; height: 200px;" :src="$urlImage + good.imgSrc" fit="fill"/>
              <!-- 显示商品信息-->
              <div class="book-info">
                <el-popover trigger="hover">
                  <template #reference>
                    <div style="margin-bottom: 5px; font-weight: bold;">
                      {{ good.name }}
                    </div>
                  </template>
                  <div v-html="good.name"></div>
                </el-popover>
                <div style="margin-bottom: 5px; color: #666;">价格：&yen;{{ good.price }}</div> <!--&yen;符号¥-->
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <!-- 分页组件 -->
    <el-row>
      <el-col :span="24" style="text-align: center">
        <el-pagination background layout="prev, pager, next, jumper"
                       :current-page="param.pageNum"
                       :page-size="param.pageSize"
                       :total="topPage.total"
                       @current-change="handleChangePage"/>
      </el-col>
    </el-row>
    <!-- 查看详情对话框，默认不可见 -->
    <el-dialog v-model="visibleInner" title="商品详情" @close="handlerClose">
      <div class="dialog-content">
        <div class="book-image">
          <img :src="$urlImage + good.imgSrc" alt="商品详情">
        </div>
        <div class="book-info">
          <h2 class="title">{{ good.name }}</h2>
          <p class="price">价格：&yen;{{ good.price }}</p>
          <el-divider></el-divider>
          <p class="intro">{{ good.detail }}</p>
          <div class="button-group">
            <el-button type="success" size="default" @click="addCart(good.id)">
              <el-icon><ShoppingCartFull/></el-icon>加入购物车</el-button>
            <el-button type="danger" size="default" @click="buy(good)">立即购买</el-button>
            <!--            <el-button type="primary" size="medium" @click="handlerClose">-->
            <!--              <el-icon :size="18">-->
            <!--                <Close/>-->
            <!--              </el-icon>-->
            <!--              关闭-->
            <!--            </el-button>-->
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 主容器的背景和内边距 */
div {
  background-color: #f9f9f9; /* 浅灰色背景 */
  padding: 5px;
}

/* 书籍信息区域 */
.book-info {
  padding: 5px; /* 调整内边距 */
  font-size: 14px; /* 字体大小 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px; /* 最大宽度 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

/* 每本书卡片 */
.el-card {
  transition: box-shadow 0.3s ease; /* 添加过渡效果 */
}

/* 鼠标悬停时添加阴影 */
.el-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); /* 更显著的阴影效果 */
}

/* 书名、价格、作者、销量样式 */
.book-info div {
  margin: 3px 0; /* 上下间距减小 */
  color: #333; /* 深色文字 */
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px; /* 顶部间距 */
}

/* 分页按钮的自定义样式 */
.el-pagination .el-button {
  background-color: #409EFF; /* 主色调 */
  color: white; /* 文字颜色 */
}

/* 分页按钮悬停效果 */
.el-pagination .el-button:hover {
  background-color: #66b1ff; /* 悬停时颜色变化 */
  color: white;
}

/* 图片样式 */
.el-image {
  border-radius: 8px; /* 圆角效果 */
  overflow: hidden; /* 防止超出 */
}

/* 对话框内容样式 */
.dialog-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.book-image {
  width: 30%;
  text-align: center;
}

.book-image img {
  max-width: 100%;
  height: auto;
}

.book-info {
  width: 68%;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 6px;
}

.author {
  font-size: 18px;
  margin: 0 0 4px;
}

.publisher,
.price {
  font-size: 16px;
  margin: 0 0 2px;
}

.intro {
  font-size: 14px;
  margin: 0 0 10px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
}
</style>